package phone.qyg.com.qyg.activity;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.application.QXApplication;
import com.app.base.tool.BaseActivity;
import com.app.config.AppHttpKey;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.JSONTool;
import com.app.utils.OptionImageUtils;
import com.app.utils.PromptManager;
import com.app.utils.ShareOtherUtils;
import com.app.utils.TransformController;
import com.app.view.ItemImageView;
import com.umeng.socialize.ShareAction;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.text.MessageFormat;
import java.util.List;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.activity.baidu.MapActivity;
import phone.qyg.com.qyg.adapter.DiscussAdapter;
import phone.qyg.com.qyg.model.Activity;
import phone.qyg.com.qyg.model.ActivityDetail;
import phone.qyg.com.qyg.model.Base;
import phone.qyg.com.qyg.model.CollectionItem;
import phone.qyg.com.qyg.model.MapItem;
import phone.qyg.com.qyg.model.MyActivity;
import phone.qyg.com.qyg.model.Roll;
import phone.qyg.com.qyg.model.VenueDetail;
import phone.qyg.com.qyg.utils.AppHttpRequest;
import phone.qyg.com.qyg.utils.DiscussUtil;

/**
 * 作者：lblbh on 2017/11/30 18:40
 * 邮箱：lanbuhan@163.com
 * 功能：活动详情
 */
@ContentView(R.layout.activity_detail)
public class ActivityDetailActivity extends BaseActivity {

    String PERSON_COUNT = "已<font color='#ff6633'>{0}</font>人预约({1})";
    String DISCUSS_COUNT = "共<font color='#ff6633'>{0}</font>条评论";

    @ViewInject(R.id.back)
    TextView back;

    @ViewInject(R.id.share)
    TextView share;

    @ViewInject(R.id.chollect)
    TextView chollect;

    @ViewInject(R.id.title)
    TextView title;

    @ViewInject(R.id.detail_map)
    TextView detail_map;

    @ViewInject(R.id.detail_phone)
    TextView detail_phone;

    @ViewInject(R.id.detail_time_state)
    TextView detail_time_state;

    @ViewInject(R.id.detail_time_end)
    TextView detail_time_end;

    @ViewInject(R.id.detail_computer)
    TextView detail_computer;

    @ViewInject(R.id.detail_person)
    TextView detail_person;

    @ViewInject(R.id.summary)
    TextView summary;

    @ViewInject(R.id.more_info)
    TextView more_info;

    @ViewInject(R.id.discuss_count)
    TextView discuss_count;

    @ViewInject(R.id.discuss_more)
    TextView discuss_more;

    @ViewInject(R.id.discuss_recycler)
    RecyclerView discuss_recycler;

    @ViewInject(R.id.act_state)
    RelativeLayout act_state;

    @ViewInject(R.id.send_discuss)
    RelativeLayout send_discuss;

    @ViewInject(R.id.regis)
    RelativeLayout regis;

    @ViewInject(R.id.item_img)
    ItemImageView item_img;

    ShareAction mShareAction;

    ActivityDetail model;

    int id;

    @Override
    public void initSucessView() {
        Object obj = getTransModels();
        if(obj instanceof Activity){
            Activity act = (Activity) obj;
            id = act.id;
        }else if(obj instanceof Base){
            Base base = (Base) obj;
            id = base.id;
        }else if(obj instanceof MapItem){
            MapItem mapItem = (MapItem) obj;
            id = mapItem.objectId;
        }else if(obj instanceof VenueDetail){
            VenueDetail venueDetail = (VenueDetail) obj;
            id = venueDetail.id;
        }else if(obj instanceof CollectionItem){
            CollectionItem collItem = (CollectionItem) obj;
            id = collItem.objectId;
        }else if (obj instanceof Roll) {
            Roll roll = (Roll) obj;
            id = roll.objectId;
        }else if(obj instanceof MyActivity){
            MyActivity myAct = (MyActivity) obj;
            id= myAct.actId;
        }
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        if(id == 0) return;
        mapKeys.put(AppHttpKey.ACT_ID,String.valueOf(id));
        AppHttpRequest.httpRequestDefalut(ApplicationConfig.ACT_DETAIL,
                mapKeys,
                new AppHttpRequest.OnAppHttpListener() {
                    @Override
                    public void onAppHttpState(boolean isState, String result) {
                        if(isState){
                            if(JSONTool.isStatus(result)){
                                model = JSONTool.jsonDefaluTranClazz(result,null, ActivityDetail.class);
                                setData();
                            }else{
                                PromptManager.showToast(JSONTool.errorHint(result));
                            }
                        }else{
                            PromptManager.showToast(R.string.service_error);
                        }
                    }
                });

        initDiscuss();
    }

    private void setData(){
        if(model == null)return;
        back.setText(CommonUtil.setAttributeText(model.title));
        title.setText(CommonUtil.setAttributeText(model.title));
        detail_map.setText(new StringBuffer(getString(R.string.map_key)).append(CommonUtil.setAttributeText(model.address)));
        detail_phone.setText(new StringBuffer(QXApplication.getContext().getResources().getString(R.string.act_phone_key)).
                                                append(CommonUtil.setAttributeText(model.phone)));
        detail_time_state.setText(new StringBuffer(getString(R.string.act_reigs_key)).
                                    append(CommonUtil.setAttributeText(model.signEndTime)));
        detail_time_end.setText(new StringBuffer(getString(R.string.act_start)).
                                    append(CommonUtil.setAttributeText(model.startTime)).
                                    append("\n").
                                    append(getString(R.string.act_end)).
                                    append(CommonUtil.setAttributeText(model.endTime)));

        act_state.setBackgroundResource((isRequestStr(model.actDeclare)?R.color.act_state_click:R.color.shallow_black));
        regis.setBackgroundResource(((model.applyBtn == 1)?R.color.act_regis:R.color.shallow_black));

        CommonUtil.setTextViewDrawableDirection(chollect,4,
                (model.isCollection == 0)?
                        R.drawable.title_collect_normal:
                        R.drawable.title_collect_select);

        detail_computer.setText(new StringBuffer(getString(R.string.computer_key)).append(CommonUtil.setAttributeText(model.sponsor)));

        summary.setText(CommonUtil.setAttributeText(model.speaker));
        CommonUtil.textViewSetText(detail_person, MessageFormat.format(PERSON_COUNT,model.memCount,model.limitStr));
        setImgPath(model.fixImgUrl,item_img,OptionImageUtils.getRectRatioAct());

    }

    private void initDiscuss(){
        AppHttpRequest.getDiscussList(id, 1, 1, new AppHttpRequest.OnAppHttpListener() {
            @Override
            public void onAppHttpState(boolean isState, String result) {
                if(isState){
                    if(JSONTool.isStatus(result)){
                        int count = JSONTool.requestJSONfindNameCount(result,JSONTool.Enum.DATA,JSONTool.Enum.TOTAL_COUNT);
//                        List<Discuss> discusses = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.COMMENT_LIST,Discuss.class);
                        List<Object> discusses = DiscussUtil.resultChangeList(result,id);

                        setDiscussData(discusses);
                        CommonUtil.textViewSetText(discuss_count,MessageFormat.format(DISCUSS_COUNT,count));
                    }else{
                        PromptManager.showToast(JSONTool.errorHint(result));
                    }
                }else{
                    PromptManager.showToast(R.string.service_error);
                }
            }
        });
    }

    /**
     * 设置讨论
     * @param models
     */
    private void setDiscussData(List<Object> models){
        LinearLayoutManager layoutVerManager = new LinearLayoutManager(QXApplication.getContext());
        layoutVerManager.setOrientation(LinearLayoutManager.VERTICAL);
        discuss_recycler.setLayoutManager(layoutVerManager);

        DiscussAdapter adapter = new DiscussAdapter(QXApplication.getContext(),models,ApplicationConfig.ACT);
        discuss_recycler.setAdapter(adapter);

    }

    @Event(value = {R.id.back,R.id.share,R.id.chollect,R.id.detail_map,R.id.more_info,
                    R.id.discuss_more,R.id.act_state,R.id.send_discuss,R.id.regis,
                    R.id.detail_phone})
    private void viewOnClick(View v){
        if(model == null && (v != back)){
            return;
        }
        switch (v.getId()){
            case R.id.back:
                this.finish();
                break;
            case R.id.share:
                mShareAction  =  ShareOtherUtils.shareTool(this,
                        model.shareAddress,
                        model.title,
                        model.sponsor,
                        model.fixImgUrl);
                mShareAction.open();
                break;
            case R.id.chollect:
                if(isUserLogin()){
                    final int isCollection = model.isCollection;
                    AppHttpRequest.collection(model.id, isCollection, "1", model.title, new AppHttpRequest.OnAppHttpListener() {
                        @Override
                        public void onAppHttpState(boolean isState, String result) {
                            if(isState){
                                PromptManager.showToast((isCollection == 0)?R.string.conllection_sucess:R.string.conllection_quit_sucess);
                                model.isCollection = (isCollection == 0) ? 1:0;
                                CommonUtil.setTextViewDrawableDirection(chollect,4,(model.isCollection == 0)? R.drawable.title_collect_normal: R.drawable.title_collect_select);
                            }
                        }
                    });
                }else{
                    TransformController.transformController(QXApplication.getContext(),LoginActivity.class);
                }
                break;
            case R.id.detail_map:
                TransformController.transformControllerModel(QXApplication.getContext(),MapActivity.class,model);
                break;
            case R.id.more_info:
                TransformController.transformControllerModel(QXApplication.getContext(),HtmlActivity.class,model);
                break;
            case R.id.discuss_more:
                TransformController.transformControllerModel(QXApplication.getContext(),DiscussActivity.class,model);
                break;
            case R.id.act_state:
                model.isHtml = 1;
                TransformController.transformControllerModel(QXApplication.getContext(),HtmlActivity.class,model);
                break;
            case R.id.send_discuss:
                if(isUserLogin()){
                    TransformController.transformControllerModel(QXApplication.getContext(),ReleaseDiscussActivity.class,model);
                }else{
                    TransformController.transformController(QXApplication.getContext(),LoginActivity.class);
                }
                break;
            case R.id.regis:
                if(model.applyBtn == 0){
                    PromptManager.showToast(R.string.act_end_regis_hint);
                    return;
                }

                if(isUserLogin()){
                    TransformController.transformControllerModel(QXApplication.getContext(),ActivityRegisActivity.class,model);
                }else{
                    TransformController.transformController(QXApplication.getContext(),LoginActivity.class);
                }
                break;
            case R.id.detail_phone:
                final String phoneNumber = model.phone;
                if (isRequestStr(phoneNumber)) {
                    CommonUtil.showAlertDialog(this,phoneNumber,getString(R.string.sure_phone),phoneNumber);
                } else {
                    PromptManager.showToast(R.string.stop_phone);
                }
                break;

        }
    }

    /**
     * 屏幕横竖屏切换时避免出现window leak的问题
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mShareAction.close();
    }

    @Override
    public void initViewHandler() {}

    @Override
    protected void onRestart() {
        super.onRestart();
        initDiscuss();
    }
}
